package com.czz.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czz.portal.entity.Period;
import com.czz.portal.entity.Study;
import com.czz.portal.mapper.PeriodMapper;
import com.czz.portal.mapper.StudyMapper;
import com.czz.portal.service.StudyService;
import com.czz.portal.vo.StudyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @ClassName: StudyServiceImpl
 * @Author Czz
 * @Date 2020/2/16
 * @Time 11:43
 **/
@Service
public class StudyServiceImpl extends ServiceImpl<StudyMapper, Study> implements StudyService {

    @Autowired
    StudyMapper studyMapper;

    @Autowired
    PeriodMapper periodMapper;

    @Override
    public Study getStudy(String userId, String periodId,String courseId) {
        QueryWrapper<Study> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);

        if (!StringUtils.isEmpty(periodId)){
            queryWrapper.eq("period_id",periodId);
        }

        if (!StringUtils.isEmpty(courseId)){
            queryWrapper.eq("course_id",courseId);
        }

        Study study = studyMapper.selectOne(queryWrapper);
        return study;
    }

    @Override
    @Transactional
    public void saveOrUpdateStudy(Study study) {
        //判断用户有无该课程学习记录，无则记录
        Period period = periodMapper.selectById(study.getPeriodId());

        QueryWrapper<Study> studyQueryWrapper = new QueryWrapper<>();
        studyQueryWrapper.eq("course_id",period.getCourseId());
        studyQueryWrapper.eq("user_id",study.getUserId());
        Study studyRecord = studyMapper.selectOne(studyQueryWrapper);

        String userId= study.getUserId();
        String courseId = period.getCourseId();
        String chapterId = period.getChapterId();
        String periodId = period.getPeriodId();
        String periodName = period.getPeriodName();

        //学习记录为空，则记录
        if (ObjectUtils.isEmpty(studyRecord)){
            Study temp = new Study();
            temp.setUserId(userId).setChapterId(chapterId).setCourseId(courseId).setPeriodId(periodId).setPeriodName(periodName);
            studyMapper.insert(temp);
            return;
        }

        //有学习记录，则更新
        studyRecord.setCourseId(courseId).setPeriodId(periodId).setPeriodName(periodName);
        studyMapper.updateById(studyRecord);

    }

    @Override
    public List<StudyVo> getStudyPageList(Page<StudyVo> pageParam, String userId) {
        return studyMapper.getStudyPageList(pageParam,userId);
    }
}
